<!--
 * @Author: ૮₍ ˙О˙₎ა
 * @Date: 2023-07-18 18:31:00
-->
<template>
  <div>
    <el-button type="primary" :icon="Plus" @click="addSpu">添加SPU</el-button>

    <el-table :data="spuList" border stripe>
      <el-table-column type="index" label="序号" width="80" />
      <el-table-column prop="spuName" label="SPU名称" />
      <el-table-column prop="description" label="SPU描述" />
      <el-table-column prop="address" label="操作" width="220">
        <template #default="{ row }">
          <el-button size="small" type="success" :icon="Plus" @click="addSku(row)" />
          <el-button size="small" type="warning" :icon="Edit" @click="EditSpu(row)" />
          <el-button size="small" type="primary" :icon="InfoFilled" />
          <el-button size="small" type="danger" :icon="Delete" />
        </template>
      </el-table-column>
    </el-table>

    <el-pagination
      :current-page="page"
      :page-size="limit"
      :page-sizes="[5, 10, 15, 20]"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    />
  </div>
</template>

<script lang="ts" setup>
import { reqSpuList } from '@/api/spu'
import { useCategoryStore } from '@/stores/category'
import type { IReqSpuListRecord } from '@/types/spu'
import { Plus, Edit, InfoFilled, Delete } from '@element-plus/icons-vue'
import { storeToRefs } from 'pinia'
import { ref, watch } from 'vue'
const emit = defineEmits<{
  (e: 'setState', id: number, row?: IReqSpuListRecord): void
}>()

const addSpu = () => {
  emit('setState', 2)
}

const addSku = (row: IReqSpuListRecord) => {
  emit('setState', 3, row)
}

const EditSpu = (row: IReqSpuListRecord) => {
  emit('setState', 2, row)
}
// 渲染SpuList
const categoryStore = useCategoryStore()
const { category3Id } = storeToRefs(categoryStore)

const spuList = ref<IReqSpuListRecord[]>([])

const getSpuList = async () => {
  const res = await reqSpuList(page.value, limit.value, category3Id.value as number)
  if (res.code === 200) {
    spuList.value = res.data.records
    total.value = res.data.total
  }
}

// 分页
const page = ref(1)
const limit = ref(5)
const total = ref(0)

const handleSizeChange = (val: number) => {
  limit.value = val
  getSpuList()
}
const handleCurrentChange = (val: number) => {
  page.value = val
  getSpuList()
}

watch(
  category3Id,
  (newVal) => {
    if (newVal) {
      getSpuList()
    } else {
      spuList.value = []
    }
  },
  {
    immediate: true
  }
)
</script>

<script lang="ts">
export default {
  name: 'SpuList'
}
</script>

<style lang="scss" scoped>
.el-table {
  margin-top: 10px;
}
.el-pagination {
  margin-top: 10px;
  display: flex;
  justify-content: center;
}
</style>
